package client

import (
	"errors"
	"fmt"
	"time"

	"git.oschina.net/gunsluo/hawkeye-common/model"
	"github.com/parnurzeal/gorequest"
	"github.com/pquerna/ffjson/ffjson"
)

type AgentClient struct {
	Url     string
	Timeout int
}

/*
	Description: 函数功能
	1、创建新上报client对象

	Author: jerrylou, <gunsluo@gmail.com>
	Since:  2016/08/25
*/
func NewAgentClient(url string, timeout int) *AgentClient {

	client := new(AgentClient)
	client.Url = url
	if timeout <= 0 {
		client.Timeout = 5
	} else {
		client.Timeout = timeout
	}

	return client
}

/*
	Description: 函数功能
	1、创建http短链接
	2、agent是http协议，不是http rpc，所以使用短链接

	Author: jerrylou, <gunsluo@gmail.com>
	Since:  2016/08/25
*/
func (this *AgentClient) newAgent() *gorequest.SuperAgent {

	timeout := time.Duration(this.Timeout) * time.Second
	return gorequest.New().Timeout(timeout).Post(this.Url)
}

/*
	Description: 函数功能
	1、http/json实现发送数据
	2、...

	Author: jerrylou, <gunsluo@gmail.com>
	Since:  2016/08/25
*/
func (this *AgentClient) Send(metrics []*model.MetricValue) error {

	buf, err := ffjson.Marshal(metrics)
	if err != nil {
		return err
	}

	request := this.newAgent()
	_, body, errs := request.Send(string(buf)).End()
	err = ErrorsToError(errs)

	if err != nil {
		return err
	}

	if body != "success" {
		return errors.New(body)
	}

	return nil
}

func ErrorsToError(errs []error) error {
	if errs == nil || len(errs) == 0 {
		return nil
	}

	errString := ""
	for i, e := range errs {
		errString = errString + fmt.Sprintf("error %d: %s \n", i, e.Error())
	}

	return errors.New(errString)
}
